<template>

  <div class="container">
    <el-button class="back-button" type="warning" :icon="ArrowLeft" @click="goBack">返回商品列表</el-button>
    <div class="left-img">
      <div>
        <el-tabs class="left-img-border" style="height: 600px">
          <el-tab-pane label="User" v-for="item in img">
            <template #label>
              <div style="width: 120px; height: 120px;">
                <img
                    :src="getPath(item)"
                    style="width: 100%"
                />
              </div>
            </template>
            <img
                :src="getPath(item)"
                style="width: 100%"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <div class="right-text">
      <div class="goods-title">{{goodsData2.name}}</div>

      <!-- 添加商品评分展示 -->
      <div class="goods-rating">
        <el-rate v-model="averageRating" disabled show-score text-color="#ff9900" score-template="{value} 分" />
        <span style="margin-left: 10px;">{{averageRating}} 分（{{totalReviews}}条评论）</span>
      </div>

      <div style="margin-bottom: 26px;">{{goodsData2.description}}</div>
      <div class="goods-card">
        <div class="card-con">门店价格：<span style="margin-left: 15px; font-size: 1.1rem; color: #666; ">¥{{goodsData2.price}}</span>
          <span style="font-size: 1.5rem;font-weight: 600;color: #df0000;margin-left: 20px;">会员价:
            <span style="color: #ff9900; font-weight: 600;">¥{{Number(goodsData2.price) - 5}}</span>
          </span>
        </div>
        <div class="card-con">累计销量：{{goodsData2.sales}}</div>
        <div class="card-con">剩余库存：{{goodsData2.store}}</div>
      </div>
      <div>
        <el-form-item class="address-sel" label="选择自提点:">
          <el-select  v-model="form.region" placeholder="please select " @change="getstoreId">
            <el-option label="永辉超市" :value="2" />
            <el-option label="京东便利店" :value="1" />
          </el-select>
        </el-form-item>
      </div>
      <div>购买数量：
        <el-input-number v-model="num" :min="1" :max="10" @change="handleChange" />
      </div>
      <div class="btns3">
        <el-button :icon="Check" type="success" @click="addtocart(goodsData2.id,form.region,goodsData2.price)">加入购物车</el-button>
        <el-button v-if="alreadyCollect" :icon="Star" type="warning" @click="setCollect()">收藏该商品</el-button>
        <el-button v-else :icon="Star" type="warning"  disabled>已收藏</el-button>
      </div>
      <div>
        <el-button  :icon="ShoppingCart" style="font-weight: 500;font-size: 1.4rem; width: 255px;" type="danger" size="large" @click="addOrder(goodsData2.id,form.region,goodsData2.price)">立即下单</el-button>
      </div>
    </div>
    <el-dialog
        v-model="dialog.show"
        :title="dialog.title"
        width="450px"
        :close-on-click-modal="false">
      <Add
          v-if="dialog.show"
          @getDataById="getDataById()"
          v-model:show="dialog.show"
          :id="dialog.id"
          :num="dialog.num"
          :storeId="dialog.storeId"
          :userId="dialog.userId"
          :price="dialog.price"
          :cart="dialog.cart"/>
    </el-dialog>
  </div>
  <div class="review-section">
    <el-divider content-position="left">商品评价</el-divider>

    <!-- 评论表单 -->
    <div v-if="showReviewForm" class="review-form">
      <h3>发表评价</h3>
      <el-form :model="reviewForm">
        <el-form-item label="评分">
          <el-rate v-model="reviewForm.rating" />
        </el-form-item>
        <el-form-item label="评论内容">
          <el-input
              type="textarea"
              v-model="reviewForm.comment"
              :rows="4"
              placeholder="请写下您的使用体验..."

          />
        </el-form-item>
        <el-form-item label="上传图片">
          <el-upload
              action="/api/upload"
              list-type="picture-card"
              :on-success="handleUploadSuccess"
              :limit="3"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-button type="warning" @click="submitReview">提交评价</el-button>
      </el-form>
    </div>

    <!-- 评论列表 -->
    <div class="review-list">
      <div v-if="reviews.length === 0" class="no-reviews">
        暂无评价，成为第一个评价的人吧！
      </div>

      <div v-for="review in reviews" :key="review.id" class="review-item">
        <div class="review-header">
          <el-avatar :size="40">{{ review.username ? review.username.charAt(0) : 'U' }}</el-avatar>
          <div class="review-info">
            <span class="username">{{ review.username || '匿名用户' }}</span>
            <el-rate v-model="review.rating" disabled />
            <span class="time">{{ formatTime(review.createTime) }}</span>
          </div>
        </div>
        <p class="comment">{{ review.comment }}</p>
        <div v-if="review.imgUrl" class="review-images">
          <img
              v-for="(img, index) in review.imgUrl.split(',')"
              :key="index"
              :src="getPath(img)"
              @click="previewImage(getPath(img))"
          />
        </div>
      </div>

      <el-pagination
          v-if="totalReviews > reviewPageSize"
          v-model:current-page="reviewPage"
          :page-size="reviewPageSize"
          :total="totalReviews"
          layout="prev, pager, next"
          @current-change="getReviews"
      />
    </div>
  </div>

  <!-- 图片预览弹窗 -->
  <el-dialog v-model="previewVisible" title="图片预览">
    <img :src="previewImageUrl" style="width: 100%">
  </el-dialog>
</template>

<script setup>
import { getCookieForObject,setCookiesFromObject} from '@/util';
import { onMounted,ref ,reactive, onUpdated } from 'vue'
import {Star,Check, ArrowLeft} from '@element-plus/icons-vue'
import { Search,ShoppingCart } from '@element-plus/icons-vue'
import router from '@/router';
import { ElMessage, ElMessageBox } from 'element-plus';
import Add from './add-order'
import { useRoute } from 'vue-router';
import {get,post} from '@/plugins/axios'
import { getPath } from '@/util';

const alreadyCollect=ref(true)
const dialog = reactive({
  show: false,
  title: '',
  id: null,
  num: '',
  storeId: null,
  userId: null,
  price:null,
  cart:0
})
const goodsData =[]
const goodsData2 =ref([])
const img=ref([])
const route = useRoute();
const userId=ref()
const form=reactive({
  region:''
})
const num = ref(1)
const handleChange = (value) => {
  console.log(value)
}
const getstoreId = (value) => {
  dialog.storeId = value
}



// 评论相关变量
const showReviewForm = ref(false)
const reviewForm = reactive({
  rating: 5,
  comment: '',
  images: []
})
const reviews = ref([])
const reviewPage = ref(1)
const reviewPageSize = ref(5)
const totalReviews = ref(0)
const averageRating = ref(0) // 平均评分

// 图片预览相关
const previewVisible = ref(false)
const previewImageUrl = ref('')

onMounted(()=>{
  getDataById()
  if (route.query.orderId) {
    checkCanReview(route.query.orderId)
  }
})

onUpdated(()=>{
  getAlreadyCollect()
})
// 添加返回方法
const goBack = () => {
  router.go(-1) // 返回上一页
}
init()
function addOrder(id, storeId, price) {
  getstoreId();
  let flag = checkLogin()
  if (flag && Number(goodsData2.value.store) > 0) {
    dialog.cart=0
    dialog.title = '添加订单'
    dialog.id =id
    dialog.num =num.value
    dialog.storeId=storeId
    dialog.userId=userId.value
    dialog.price=price
    dialog.show = true
  } else {
    if (Number(goodsData2.value.store) <= 0) {
      ElMessage({
        type: 'warning',
        message: '商品库存不够啦，请耐心等待商家补货'
      })
    }

  }

}

function checkCanReview(orderId) {
  get("/goodsReview/canReview", { orderId }, content => {
    showReviewForm.value = content
  })
}

function handleUploadSuccess(response, file) {
  if (response && response.data) {
    reviewForm.images.push(response.data)
  }
}

function submitReview() {
  if (!reviewForm.comment) {
    ElMessage.warning('请填写评论内容')
    return
  }

  post("/goodsReview/add", {
    'orderId': route.query.orderId,
    'productId': goodsData2.value.id,
    'userId': userId.value,
    'rating': reviewForm.rating,
    'comment': reviewForm.comment,
    'imgUrl': reviewForm.images.join(',')
  }, () => {
    ElMessage.success('评价成功！')
    showReviewForm.value = false
    // 重新获取评论和评分
    getReviews()
    getAverageRating()
  })
}

function getReviews() {
  // 获取商品评论
  get("/goodsReview/page", {
    'productId':goodsData2.value.id,
    'page': reviewPage.value,
    'size': reviewPageSize.value
  }, content => {
    reviews.value = content.records || []
    totalReviews.value = content.total || 0
  })
}

// 获取平均评分
function getAverageRating() {
  get("/goodsReview/averageRating", {
    'productId':goodsData2.value.id
  }, content => {
    // 保留一位小数
    averageRating.value = content ? parseFloat(content.toFixed(1)) : 0
  })
}

function formatTime(time) {
  if (!time) return ''
  const date = new Date(time)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 图片预览
function previewImage(url) {
  previewImageUrl.value = url
  previewVisible.value = true
}

function addtocart(id, address, price) {
  let flag = checkLogin()
  if (flag) {
    dialog.cart=1
    dialog.title = '添加到购物车'
    dialog.id =id
    dialog.num =num.value
    dialog.address=address
    dialog.userId=userId.value
    dialog.price=price
    dialog.show = true
  }
}

function getDataById(){
  get("/goods/getById", {'id':route.query.goodsId},content =>{
    goodsData.push(content)
    for(const key in content.imagePathList){
      img.value.push(content.imagePathList[key])
    }
    goodsData2.value = content

    // 获取评论和评分
    getReviews()
    getAverageRating()
  })
}

//通过cookie里的用户信息来进行初始化防止频繁访问数据库
function init(){
  const userinfo= getCookieForObject('user')
  if (userinfo) {
    userId.value=userinfo.id
  }
}

function checkLogin() {
  if (userId.value === undefined) {
    ElMessageBox.confirm('您尚未登录，请先登录。', '提示', {
      confirmButtonText: '登录',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      router.push({ name: 'LoginRegister' })
    })
    return false
  } else {
    return true
  }
}

function setCollect() {
  let flag = checkLogin()
  if (flag) {
    post("/collect/add",{goodsId:goodsData2.value.id,userId:userId.value},()=>{
      ElMessage({
        type:'success',
        message: '收藏成功',
      })
      getAlreadyCollect()
    })
  }
}

function getAlreadyCollect(){
  post("/collect/search",{goodsId:goodsData2.value.id,userId:userId.value},content=>{
    alreadyCollect.value=content
  })
}
</script>

<style lang="scss" scoped>
.back-button {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 10;

  .el-button {
    display: flex;
    align-items: center;
    gap: 5px;
    font-weight: 500;
  }
}
.container{
  display: flex;
  min-height: 100vh;
  .left-img{
    display: flex;
    margin: 30px auto;
    .left-img-border{
      border: 2px solid #f8c27f;
      padding: 16px 16px 0 16px;
      width: 400px;
    }
    .el-tabs--top{
      flex-direction: column;
    }
    .el-tabs{
      --el-tabs-header-height:100px;
      --el-font-size-base:26px;
    }
    .el-tabs__nav-prev,.el-tabs__nav-next{
      left: -6px;
      font-size: 25px;
      line-height: 106px;
    }
  }
  .right-text{
    display: flex;
    width: 60%;
    flex-direction: column;
    .goods-title{
      margin: 28px 0 10px 0;
      font-size: 28px;
      font-weight: bold;
    }
    .goods-rating {
      display: flex;
      align-items: center;
      margin-bottom: 15px;
      font-size: 16px;
      color: #676666;
    }
    .goods-card{
      width: 800px;
      height: 180px;
      background-color: #fff5e9;
      border-radius: 6px;

      .card-con{
        margin: 30px 26px;
        font-size: 16px;
      }
    }
    .address-sel{
      width: 300px;
      margin: 26px 0 26px 0;
    }
    .btns3{
      margin: 26px 0 26px 0;
    }
  }
}
::v-deep .el-tabs__nav-next{
  font-size: 1.5rem;
  font-weight: 600;
  line-height: 100px;
}
::v-deep .el-tabs__nav-prev{
  font-size: 1.5rem;
  font-weight: 600;
  line-height: 100px;
}
.review-section {
  margin-top: 50px;
  padding: 20px;
  border-top: 1px solid #eee;
}

.review-form {
  background: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 30px;
background-color: #fff5e9;
  h3 {
    margin-bottom: 20px;
    font-size: 18px;
    color: #333;
  }
}

.review-item {
  border-bottom: 1px solid #fff5e9;
  padding: 20px 0;
}

.review-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.review-info {
  margin-left: 15px;
  flex: 1;
  display: flex;
  align-items: center;
}

.username {
  font-weight: bold;
  margin-right: 15px;
}

.time {
  color: #999;
  font-size: 0.9rem;
  margin-left: auto;
}

.comment {
  margin: 10px 0;
  line-height: 1.6;
  font-size: 15px;
  color: #333;
}

.review-images img {
  width: 100px;
  height: 100px;
  object-fit: cover;
  margin-right: 10px;
  border-radius: 4px;
  cursor: pointer;
  transition: transform 0.3s;

  &:hover {
    transform: scale(1.05);
  }
}

.no-reviews {
  text-align: center;
  padding: 40px 0;
  color: #7e4f4f;
  font-weight: bold;
  font-size: 16px ;
}

.el-pagination {
  margin-top: 20px;
  justify-content: center;
}
.back-button {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 10;
}
</style>